<template>
  <el-dialog
    :title="form.id?$t('message.edit') + $t('message.gdyd'):$t('message.gdyd')"
    :visible.sync="show"
    width="750px"
    :close-on-click-modal="modalDialog"
    :close-on-press-escape="modalDialog"
    @close="closeDialog"
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="auto" label-suffix="：">
      <el-form-item :label="$t('message.memberInfo')" prop="memberId">
        <MemberSearch v-if="!form.id" ref="memberSearch" @clear="memberClear" @select="memberSelect" />
        <div v-if="memberInfo && memberInfo.nickName" :class="form.id?'member wu': 'member'">
          <div>{{ $t('message.name') }}：{{ memberInfo.nickName }}</div>
          <div>{{ $t('message.sjh') }}：{{ memberInfo.phone }}</div>
          <div>{{ $t('message.hydj') }}：{{ memberInfo.cardName }}</div>
          <div>{{ $t('message.czje') }}：<span>{{ memberInfo.rechargeMoney || 0 }}</span></div>
          <div>{{ $t('message.zsye') }}：<span>{{ memberInfo.giveMoney || 0 }}</span></div>
        </div>
      </el-form-item>

      <el-form-item :label="$t('message.gdrq')" prop="date">
        <el-date-picker
          v-model="form.date"
          class="w400"
          value-format="yyyy-MM-dd"
          type="daterange"
          :range-separator="$t('message.zhi')"
          :start-placeholder="$t('message.ksrq')"
          :end-placeholder="$t('message.jsrq')"
          :picker-options="pickerOptions"
          @change="timeChane"
        />
      </el-form-item>
      <el-form-item :label="$t('message.ydcc')" prop="ydcc">
        <div v-for="(em, dex) in siteDatas" :key="dex" class="ccLi">
          <el-select v-model="em.siteId" :placeholder="$t('message.qxz') + $t('message.cd')" style="width: 30%;margin-right: 1%;" @change="timeChane">
            <el-option v-for="item in cdList" :key="item.id" :label="item.siteName" :value="item.id" />
          </el-select>
          <el-select v-model="em.week" :placeholder="$t('message.qxz') + $t('message.xinqi')" style="width: 30%;margin-right: 1%;" @change="timeChane">
            <el-option v-for="item in weekList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
          <el-select v-model="em.time" :placeholder="$t('message.qxz') + $t('message.sjd')" style="width: 30%;" @change="timeChane">
            <el-option v-for="(item, index) in timeSlotList" :key="index" :label="item" :value="item" />
          </el-select>
          <span class="delBtn" @click="delBtn(em, dex)">{{ $t('message.del') }}</span>
        </div>
        <div class="addBtn" @click="addBtn">+{{ $t('message.zjcc') }}</div>
      </el-form-item>
      <el-form-item v-if="timeList && timeList.length > 0" :label="$t('message.yxcc')" prop="qeqw">
        <div class="yxCnt">
          <div v-for="(item, index) in timeList" :key="index">{{ item }}</div>
        </div>
      </el-form-item>
      <el-form-item :label="$t('message.zdkk')" prop="payStatue">
        <el-switch
          v-model="form.payStatue"
          :active-value="'1'"
          :inactive-value="'0'"
        />
      </el-form-item>
      <el-form-item :label="$t('message.bz')">
        <el-input
          v-model="form.remarks"
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 10 }"
          maxlength="200"
          :placeholder="$t('message.qsr') + $t('message.bzxx')"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">{{ $t('message.qx') }}</el-button>
      <el-button :loading="loading" type="primary" @click="clickPlsc">{{ $t('message.qr') }}</el-button>
    </div>
  </el-dialog>
</template>
<script>
import {
  getTimeQuantumBySite,
  memberDetailInfo,
  updateOrAddFixationSiteReserve
} from '@/api'
import { shortcuts } from '@/utils/config'
import store from '@/store'
import MemberSearch from '@/components/MemberSearch'
export default {
  components: {
    MemberSearch
  },
  data() {
    return {
      modalDialog: store.getters.dialog,
      pickerOptions: {
        shortcuts,
        disabledDate(time) {
          return (
            time.getTime() < new Date(new Date().toLocaleDateString()).getTime()
          )
        }
      },
      cdList: [],
      show: false, // 弹窗
      form: {},
      siteDatas: [{}],
      timeSlotList: [],
      projectId: '',
      memberInfo: {},
      timeList: [],
      weekList: [{
        label: this.$t('message.z1'),
        value: '1'
      }, {
        label: this.$t('message.z2'),
        value: '2'
      }, {
        label: this.$t('message.z3'),
        value: '3'
      }, {
        label: this.$t('message.z4'),
        value: '4'
      }, {
        label: this.$t('message.z5'),
        value: '5'
      }, {
        label: this.$t('message.z6'),
        value: '6'
      }, {
        label: this.$t('message.z7'),
        value: '7'
      }],
      loading: false,
      rules: {
        memberId: [
          { required: true, message: this.$t('message.qxz') + this.$t('message.hy'), trigger: 'change' }
        ],
        date: [
          { required: true, message: this.$t('message.qxz') + this.$t('message.gdrq'), trigger: 'change' }
        ],
        ydcc: [
          { required: true, message: this.$t('message.qxz') + this.$t('message.ydcc'), trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    togGetTimeQuantumBySite() {
      getTimeQuantumBySite({ param: { projectId: this.projectId }}).then(
        (res) => {
          if (res.errorCode === '000000') {
            this.cdList = res.recordList || []
            if (res.recordList && res.recordList.length > 0) {
              this.timeSlotList = res.recordList[0].times
            } else {
              this.timeSlotList = []
            }
            this.timeChane()
          }
        }
      )
    },
    getWeek(begin, end, weekNum) {
      var dateArr = []
      var stimeArr = begin.split('-')// =>["2018", "01", "01"]
      var etimeArr = end.split('-')// =>["2018", "01", "30"]
      // console.log(stimeArr,etimeArr);

      var stoday = new Date()
      stoday.setUTCFullYear(stimeArr[0], stimeArr[1] - 1, stimeArr[2])
      var etoday = new Date()
      etoday.setUTCFullYear(etimeArr[0], etimeArr[1] - 1, etimeArr[2])

      var unixDb = stoday.getTime()// 开始时间的毫秒数
      var unixDe = etoday.getTime()// 结束时间的毫秒数

      for (var k = unixDb; k <= unixDe;) {
        const needJudgeDate = this.msToDate(parseInt(k)).withoutTime
        // 不加这个if判断直接push的话就是已知时间段内的所有日期
        if (new Date(needJudgeDate).getDay() === weekNum) {
          dateArr.push(needJudgeDate)
        }
        k = k + 24 * 60 * 60 * 1000
      }
      return dateArr
    },
    timeChane() {
      let arr = this.siteDatas || []
      arr = this.noRepeat(arr)
      this.siteDatas = arr
      let pd = false
      arr.forEach(e => {
        if (e.siteId && e.time && e.week) {
          pd = true
        }
      })
      if (pd) {
        this.$set(this.form, 'ydcc', '1')
        this.$nextTick(() => {
          setTimeout(() => {
            this.$refs.form.clearValidate()
          }, 300)
        })
      } else {
        this.$set(this.form, 'ydcc', '')
      }
      if (this.form.date && this.form.date.length > 0) {
        const timeList = []
        arr.forEach(e => {
          if (e.siteId && e.time && e.week) {
            let weeks = Number(e.week)
            if (weeks === 7) {
              weeks = 0
            }
            const week = this.getWeek(this.form.date[0], this.form.date[1], weeks)
            week.forEach(s => {
              const obj = s.substr(5, 10) + ' ' + this.weekName(e.week) + ' ' + this.cdName(e.siteId) + ' ' + e.time
              timeList.push(obj)
            })
          }
        })
        this.timeList = timeList
      } else {
        this.timeList = []
      }
    },
    noRepeat(arr) {
      // 缓存用于记录
      const newArr = []
      for (const t of arr) {
        // 检查缓存中是否已经存在
        if (
          newArr.find(
            (c) =>
              c.time === t.time &&
                c.siteId === t.siteId &&
                c.week === t.week
          )
        ) {
          // 已经存在说明以前记录过，现在这个就是多余的，直接忽略
          this.$message.info(this.$t('message.tysjdbyxcxlc'))
          continue
        }
        // 不存在就说明以前没遇到过，把它记录下来
        newArr.push(t)
      }

      // 记录结果就是过滤后的结果
      return newArr
    },
    weekName(value) {
      const obj = this.weekList.find(item => item.value === value)
      if (obj) {
        return obj.label
      } else {
        return '-'
      }
    },
    cdName(value) {
      const obj = this.cdList.find(item => item.id === value)
      if (obj) {
        return obj.siteName
      } else {
        return '-'
      }
    },

    // 根据毫秒数获取日期
    msToDate(msec) {
      const datetime = new Date(msec)
      const year = datetime.getFullYear()
      const month = datetime.getMonth()
      const date = datetime.getDate()
      const hour = datetime.getHours()
      const minute = datetime.getMinutes()
      const second = datetime.getSeconds()
      const result1 = year +
               '-' +
               ((month + 1) >= 10 ? (month + 1) : '0' + (month + 1)) +
               '-' +
               ((date + 1) < 10 ? '0' + date : date) +
               ' ' +
               ((hour + 1) < 10 ? '0' + hour : hour) +
               ':' +
               ((minute + 1) < 10 ? '0' + minute : minute) +
               ':' +
               ((second + 1) < 10 ? '0' + second : second)
      const result2 = year +
               '-' +
               ((month + 1) >= 10 ? (month + 1) : '0' + (month + 1)) +
               '-' +
               ((date + 1) < 11 ? '0' + date : date)
      const result = {
        hasTime: result1,
        withoutTime: result2
      }
      return result
    },
    addBtn() {
      const arr = [...this.siteDatas]
      arr.push({})
      this.siteDatas = arr
    },
    delBtn(em, dex) {
      if (this.siteDatas.length > 1) {
        const arr = [...this.siteDatas]
        arr.splice(dex, 1)
        this.siteDatas = arr
        this.timeChane()
      } else {
        this.$message.info(this.$t('message.zsblygcc'))
      }
    },

    showBtn(projectId, b) {
      this.show = true
      this.projectId = projectId
      if (b) {
        this.form = b
        this.timeList = []
        this.siteDatas = b.siteDatas || [{}]
      } else {
        this.form = {}
        this.timeList = []
        this.memberInfo = {}
        this.siteDatas = [{}]
      }
      this.togGetTimeQuantumBySite()
      this.$nextTick(() => {
        if (b && b.memberId) {
          this.memberDetail(b)
          this.timeChane()
        } else {
          this.$refs.memberSearch.clearSearch()
          this.$refs.form.clearValidate()
        }
      })
    },
    memberDetail(item) {
      memberDetailInfo({ param: { memberId: item.memberId }}).then((res) => {
        if (res.errorCode !== '000000') return
        this.memberInfo = res.record || {}
      })
    },
    memberSelect(item) {
      this.memberInfo = item
      this.$set(this.form, 'memberId', item.id)
      this.$refs.form.clearValidate()
    },
    memberClear() {
      this.memberInfo = {}
      this.$set(this.form, 'memberId', '')
    },
    closeDialog() {
      this.$refs.form.resetFields()
      this.$emit('close')
      this.show = false
    },
    clickPlsc() {
      const that = this
      const param = { ... this.form }
      const arr = [...this.siteDatas]
      const siteDatas = []
      arr.forEach(e => {
        if (e.siteId && e.time && e.week) {
          siteDatas.push(e)
        }
      })
      this.$refs.form.validate((valid) => {
        if (valid) {
          that.loading = true
          updateOrAddFixationSiteReserve({
            param: {
              memberId: param.memberId,
              payStatue: param.payStatue ? param.payStatue : '0',
              startDay: param.date[0],
              endDay: param.date[1],
              id: param.id,
              siteDatas,
              projectId: that.projectId,
              remarks: param.remarks
            }
          }).then(res => {
            that.loading = false
            if (res.errorCode === '000000') {
              if (param.id) {
                that.$message.success(this.$t('message.xggdydcg'))
              } else {
                that.$message.success(this.$t('message.gdydcg'))
              }
              that.show = false
              that.$emit('gdydSuccess')
            }
          }).catch(() => {
            that.loading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
@import '@/styles/variables.scss';

.member {
    width: 100%;
    background: #F7F7F7;
    border-radius: 2px;
    padding: 16px;
    box-sizing: border-box;
    display: flex;
    flex-wrap: wrap;
    margin-top: 10px;
    &.wu {
      margin-top: 0;
    }

    div {
        font-size: 13px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #222222;
        width: 33.33%;
        line-height: 1.5;

        &:nth-of-type(4),
        &:nth-of-type(5) {
            margin-top: 5px;
        }

        span {
            color: $SecondColor;
        }
    }
}

.ccLi {
    margin-bottom: 10px;

    .delBtn {
        width: 8%;
        text-align: right;
        display: inline-block;
        cursor: pointer;
        color: #666666;
        font-size: 14px;
    }
}

.addBtn {
    color: $primaryColor;
    font-size: 14px;
    line-height: 1.5;
    cursor: pointer;
}

.yxCnt {
    border: 1px solid #DFE2E8;
    box-sizing: border-box;
    padding: 10px;
    border-radius: 4px;
    width: 100%;
    display: flex;
    flex-wrap: wrap;
    max-height: 138px;
    overflow-y: auto;

    div {
        width: calc(50% - 5px);
        height: 32px;
        background: #F7F7F7;
        border-radius: 2px;
        box-sizing: border-box;
        padding: 0 10px;
        margin-top: 10px;
        line-height: 32px;
        display: -webkit-box;
-webkit-line-clamp: 1;
 -webkit-box-orient: vertical;
 overflow: hidden;

        &:nth-of-type(odd) {
            margin-right: 10px;
        }

        &:nth-of-type(1),
        &:nth-of-type(2) {
            margin-top: 0;
        }
    }
}
</style>

